// AppState.h

#ifndef __APP_STATE_H
#define __APP_STATE_H

#include "Common/System/Threading/Utility.h"

#include "ViewSettings.h"

void inline AddUniqueStringToHead(CStringVector &list,
								  const CString &string)
{
	for(size_t i = 0; i < list.size();)
		if (string.CompareNoCase(list[i]) == 0)
		{
			list.erase(list.begin() + i);
		}
		else
		{
			i++;
		}
	list.push_front(string);
}

class CFastFolders
{
	CComAutoCriticalSection _criticalSection;
public:
	CStringVector Strings;
	void SetString(size_t index, const CString &string)
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		while(Strings.size() <= index)
		{
			Strings.push_back(CString());
		}
		Strings[index] = string;
	}
	CString GetString(size_t index)
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		if (index >= Strings.size())
		{
			return CString();
		}
		return Strings[index];
	}
	void Save()
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		SaveFastFolders(Strings);
	}
	void Read()
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		ReadFastFolders(Strings);
	}
};

class CFolderHistory
{
	CComAutoCriticalSection _criticalSection;
	CStringVector Strings;
	void Normalize()
	{
		const int kMaxSize = 100;
		if (Strings.size() > kMaxSize)
		{
			Strings.erase(Strings.begin() + kMaxSize, Strings.end());
		}
	}

public:

	void GetList(CStringVector &foldersHistory)
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		foldersHistory = Strings;
	}

	void AddString(const CString &string)
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		AddUniqueStringToHead(Strings, string);
		Normalize();
	}

	void RemoveAll()
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		Strings.clear();
	}

	void Save()
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		SaveFolderHistory(Strings);
	}

	void Read()
	{
		Common::System::Threading::CComScopeAutoLock lock(_criticalSection);
		ReadFolderHistory(Strings);
		Normalize();
	}
};

struct CAppState
{
	CFastFolders FastFolders;
	CFolderHistory FolderHistory;
	void Save()
	{
		FastFolders.Save();
		FolderHistory.Save();
	}
	void Read()
	{
		FastFolders.Read();
		FolderHistory.Read();
	}
};

#endif
